package gptma.bo.services.scheduling;

import java.util.Collection;
import java.util.Date;

import gptma.bo.auth.UserRoles;

import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Stateless
@RolesAllowed({ UserRoles.ROLE_ADMIN, UserRoles.ROLE_CHIEF })
public class SchedulingServicesImpl implements SchedulingServices {

	private static final Logger log = LoggerFactory
			.getLogger(SchedulingServicesImpl.class);

	@Resource
	private TimerService timerService;

	@Resource(mappedName = "jms/ConnectionFactory")
	private ConnectionFactory connectionFactory;

	@Resource(mappedName = "jms/Topic")
	private Topic topic;

	@Override
	public void startProbe() {
		timerService.createTimer(1000, 5000, null);
	}

	@Override
	public void stopProbe() {
		Collection<Timer> timers = timerService.getTimers();
		for (Timer timer : timers) {
			timer.cancel();
		}
	}

	@Timeout
	public void doProbe(Timer timer) {
		log.debug("Begin");

		log.info("Next timeout at {}", timer.getNextTimeout());

		final String message = "Hello from Timer emitted at " + new Date();
		log.info("Attempting to send following message to JMS topic: {}", message);

		try {
			Connection con = connectionFactory.createConnection();
			Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
			TextMessage msg = sess.createTextMessage(message);
			MessageProducer producer = sess.createProducer(topic);
			producer.send(msg);
		} catch (JMSException e) {
			log.error("Could not post message to JMS topic, error code: {}, msg: {}",
					e.getErrorCode(), e.getMessage());
		}

		log.debug("End");
	}

}
